import React, { useState, useEffect, useReducer } from 'react';
import { Modal, message, Spin, Space, Select, InputNumber, Tag } from 'antd';
import { useDrag, useDrop, useRequest } from 'ahooks';
import { cloneDeep } from 'lodash';
import { IAreaLiftingControl, getLiftingControlByArea } from 'api/LiftControl';
import { updateLiftGroup, addLiftGroup } from 'api/LiftingGroup';
import { IArea } from 'api/Area';
interface IGroupModalProps {
    visible: boolean;
    toggleVisible: (value: boolean) => void;
    areas: IArea[];
    selectedArea?: number;
    refresh: Function
}
const GroupEdit = (props: IGroupModalProps) => {
    const [groupArea, setGroupArea] = useState(-1); // 分组弹框区域
    const [groupNumber, setGroupNumber] = useState(2); // 分组弹框分组数量
    const [groupLifts, setGroupLifts] = useState<any>({}); // 分组信息
    const [groupResult, setGroupResult] = useState<any>(); // 分组结果
    const [groupLiftOrderMap, setGroupLiftOrderMap] = useState<any>({});
    const [groupLiftControls, setGroupLiftControls] = useState<IAreaLiftingControl>();
    /** 获取区域内控制箱，分组弹框 */
    const { run: getLiftingControlByAreaRun, loading: getLiftingControlByAreaLoading } = useRequest(
        () => getLiftingControlByArea({ areaId: groupArea === -1 ? props.selectedArea : groupArea }),
        {
            manual: true,
            onSuccess(res) {
                setGroupLiftControls(res);
                // 获取区域内控制箱信息
                if (!res.groupFlag) {
                    // 未分组
                    let obj: any = {};
                    let orderMap: any = {};
                    res.liftings?.map((lift) => {
                        obj[lift.orderNum] = '';
                        orderMap[lift.orderNum] = lift.id;
                    });
                    setGroupLiftOrderMap(orderMap);
                    setGroupLifts(obj);
                    setGroupResult({
                        1: [],
                        2: [],
                    });
                    setGroupNumber(2);
                } else {
                    // 已分组
                    let newGroupLifts: any = {};
                    let newGroupResult: any = {};
                    let orderMap: any = {};
                    res.group?.map((group, index) => {
                        newGroupResult[index + 1] = group.liftings.map((lift) => {
                            newGroupLifts[lift.orderNum] = index + 1;
                            orderMap[lift.orderNum] = lift.id;
                            return lift.orderNum;
                        });
                    });
                    setGroupLiftOrderMap(orderMap);
                    setGroupNumber(res.group?.length || 2);
                    setGroupLifts(newGroupLifts);
                    setGroupResult(newGroupResult);
                }
            },
        },
    );
    const getDragProps = useDrag();
    const [dropProps] = useDrop({
        onDom: (content: string, e) => {
            let id = (e?.target as any).id;
            groupLifts[content] = id.split('-')[1];
            setGroupLifts(groupLifts);
            let result: any = {};
            Object.keys(groupLifts).forEach((key) => {
                if (groupLifts[key] === '') return;
                if (result[groupLifts[key]]) {
                    result[groupLifts[key]].push(key);
                } else {
                    result[groupLifts[key]] = [key];
                }
            });
            setGroupResult(result);
            console.log('result', result);
        },
    });

    useEffect(() => {
        if (!props.visible) {
            setGroupArea(-1)
            return
        }
        if (!props.selectedArea) return
        setGroupArea(props.selectedArea)
    }, [props.visible, props.selectedArea])

    /** 分组时切换区域 */
    useEffect(() => {
        if (groupArea === -1) return;
        getLiftingControlByAreaRun();
    }, [groupArea, getLiftingControlByAreaRun]);

    /** 取消柱子 */
    const resetLift = (id: string, group: number) => {
        let newGroupLifts = cloneDeep(groupLifts);
        newGroupLifts[id] = '';
        groupResult[group] = groupResult[group].filter((item: any) => item !== id);
        setGroupLifts(newGroupLifts);
        setGroupResult(groupResult);
    };
    /** 分组数量变化 */
    const groupNumberChange = (value: any) => {
        setGroupNumber(Number(value) || 2);
        let groupLiftsCopy = cloneDeep(groupLifts);
        let groupResultCopy = cloneDeep(groupResult);
        Object.keys(groupResultCopy).map((number) => {
            if (Number(number) > value) {
                groupResultCopy[number]?.map((item: string) => (groupLiftsCopy[item] = ''));
                groupResultCopy[number] = [];
            }
        });
        setGroupLifts(groupLiftsCopy);
        setGroupResult(groupResultCopy);
    };
    const onOk = () => {
        let result = Object.keys(groupLifts).some((key) => groupLifts[key] === '');
        if (result) {
            // 未分组的自动分组
            Object.keys(groupLifts).map((key) => {
                if (!groupLifts[key]) {
                    groupLifts[key] = groupNumber + 1;
                    if (groupResult[groupNumber + 1]) {
                        groupResult[groupNumber + 1].push(+key);
                    } else {
                        groupResult[groupNumber + 1] = [+key];
                    }
                }
            });
            setGroupLifts(groupLifts);
            setGroupResult(groupResult);
            console.log(groupLifts, groupResult);
        }
        const notEmptyResult = Object.keys(groupResult).filter((key) => groupResult[key].length > 0);
        let obj: any;
        if (notEmptyResult.length === 1) {
            return message.warning('至少分为两组');
        } else if (notEmptyResult.length === 2 && result) {
            // 有未分组的，自动分为两组的
            if (groupResult[1]) {
                obj = {
                    1: groupResult[1],
                    2: groupResult[3],
                };
            } else {
                obj = {
                    1: groupResult[3],
                    2: groupResult[2],
                };
            }
            setGroupResult(obj);
        } else {
            obj = groupResult;
        }
        let groupForm: any = [];
        Object.keys(obj).map((groupName) => {
            let ids = obj[groupName].map((orderNum: any) => groupLiftOrderMap[orderNum]);
            groupForm.push({
                name: groupName,
                areaId: groupArea,
                liftingIds: ids,
            });
        });
        console.log(groupForm);
        if (groupLiftControls?.groupFlag) {
            // 已分组，更新
            updateLiftGroup(groupForm).then(() => {
                message.success('分组成功');
                props.toggleVisible(false);
                props.refresh()
            });
        } else {
            addLiftGroup(groupForm).then(() => {
                // 未分组
                message.success('分组成功');
                props.toggleVisible(false);
                props.refresh()
            });
        }
    };
    const onCancel = () => {
        props.toggleVisible(false);
    };

    return (
        <Modal
            visible={props.visible}
            width="50%"
            title="分组管控"
            okText="确定"
            cancelText="取消"
            onOk={onOk}
            onCancel={onCancel}
            destroyOnClose
            okButtonProps={{ disabled: false }}
            className="group-modal"
        >
            <Spin spinning={getLiftingControlByAreaLoading}>
                <Space className="mb20">
                    <span>区域分布：</span>
                    <Select
                        style={{ width: 200 }}
                        allowClear
                        value={groupArea}
                        onChange={(value) => setGroupArea(value)}
                    >
                        {props.areas.map((area: IArea) => (
                            <Select.Option key={area.id} value={area.id || -1}>
                                {area.name}
                            </Select.Option>
                        ))}
                    </Select>
                    <span>分组数量：</span>
                    <InputNumber min={2} max={6} value={groupNumber} onChange={groupNumberChange} />
                </Space>
                <Space className="mb20" style={{ width: '100%', overflowX: 'auto' }}>
                    {Object.keys(groupLifts).map((id) => (
                        <div key={id} className={groupLifts[id] ? 'grouped-lifts' : ''}>
                            <div className="text-center">{id}</div>
                            <img
                                {...getDragProps(`${id}`)}
                                className="lifting-control"
                                src={require('assets/imgs/lift-up.png')}
                                alt=""
                            />
                        </div>
                    ))}
                </Space>
                <Space className="group-box-row">
                    {new Array(groupNumber).fill(1).map(({}, index) => (
                        <div key={index}>
                            <div id={'box-' + (index + 1)} className="group-box-title" {...dropProps}>
                                分组{index + 1}
                                <br />
                                说明：将上方编号路桩拖入框内即为一组,非选中编号路桩将自动划为一组
                            </div>
                            <div className="group-area">
                                {groupResult?.[index + 1]?.map((id: any) => (
                                    <Tag key={id} closable onClose={() => resetLift(id, index + 1)}>
                                        {id}
                                    </Tag>
                                ))}
                            </div>
                        </div>
                    ))}
                </Space>
            </Spin>
        </Modal>
    );
};
export default GroupEdit;
